package org.svgweb;
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.Sprite;
import flash.events.EventDispatcher;
import flash.events.MouseEvent;
import flash.external.ExternalInterface;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.Lib;
import flash.xml.XML;
import me.cunity.debug.Out;
import org.svgweb.core.SVGNode;
import org.svgweb.events.SVGEvent;
import org.svgweb.core.SVGViewer;
import org.svgweb.utils.SVGUnits;
using me.cunity.tools.XMLTools;

/**
 * ...
 * @author axel@cunity.me
 */

class SVGLayout extends SVGViewer
{

	var box:Rectangle;	
	var layoutCallback:Void->Void;
		
	public function new(?cB:Void->Void=null) 
	{
		//layoutInfo = new Hash();
		super();
		layoutCallback = cB;
		//TODO CHECK 4 EXISTENCE OF JS loadURL
		if(ExternalInterface.available)
			ExternalInterface.addCallback('loadURL', loadURL);
			//trace('loadURL callback added');
	}
        
	
	public function layout(evt:SVGEvent)
	{
		//trace(layoutCallback);
		svgRoot.removeEventListener(SVGEvent.SVGLoad, layout);
		if (layoutCallback != null)
		{
			layoutCallback();
			return;
		}
		//return;
		if (box == null)
			box = new Rectangle(5, 5, stage.stageWidth - 10, stage.stageHeight - 10);
		Lib.current.graphics.lineStyle(1, 0xffffff);
		Lib.current.graphics.beginFill(0xffffff, 0);
		Lib.current.graphics.drawRect(5,5,stage.stageWidth-10, stage.stageHeight-10);
		var rootBox	= layoutRootNode == null ? svgRoot.topSprite.getBounds(this) :
			layoutRootNode.topSprite.getBounds(this) ;
		trace(box.toString()+ ' LayoutRoot:'  +layoutRootNode );
		//trace(box.toString()+ ' LayoutRoot:'  +layoutRootNode + ':' + layoutRootNode.getGuid());
		trace(rootBox.toString());
		trace(getWidth() + ' x ' + getHeight());
		if (false && svgRoot.getAttribute('width') != null && svgRoot.getAttribute('height') != null)
		{
			rootBox = new Rectangle(0, 0 , Std.parseFloat(svgRoot.getAttribute('width')),
				Std.parseFloat(svgRoot.getAttribute('height')));
			trace(rootBox.toString());
			var scale:Float = Math.min(box.width / rootBox.width, box.height / rootBox.height);
			svgRoot.topSprite.scaleX  = svgRoot.topSprite.scaleY = scale;
			svgRoot.topSprite.x =  5 +(box.width - rootBox.width*scale)/2;
			svgRoot.topSprite.y =  5 +(box.height - rootBox.height*scale)/2;			
		}
		
		else if (svgRoot.getAttribute('viewBox') == null)
		{
			var scale:Float = Math.min(box.width / rootBox.width, box.height / rootBox.height);
			svgRoot.topSprite.scaleX  = svgRoot.topSprite.scaleY = scale;
			var scaledBox:Rectangle = svgRoot.topSprite.getBounds(Lib.current);
			
			trace(scale +':' + rootBox.toString());
			svgRoot.topSprite.x = -rootBox.x + 5 +(box.width - rootBox.width)/2;
			svgRoot.topSprite.y = -rootBox.y + 5 +(box.height - rootBox.height)/2;
		}
		else
		{
			var viewBox:String = ~/,/sg.replace(svgRoot.getAttribute('viewBox')," "); //Replace commas with spaces
			var points:Array<Dynamic> = ~/\s+/g.split(viewBox); //Split by white space 
			var viewX = SVGUnits.parseNum(points[0]);
			var viewY = SVGUnits.parseNum(points[1]);
			var viewWidth = SVGUnits.parseNum(points[2]);
			var viewHeight = SVGUnits.parseNum(points[3]);
					
		}
		Out.dumpLayout(svgRoot.topSprite, false);
	}
	
	/*public function addLayout(layoutEl:XML, p:XML)
	{
		var info:Dynamic = { };
		//trace(p);
		//for (name in ['x','y', 'width', 'height'])
		for (name in [])
			Reflect.setField(info, name, p.getAttributeNS(name));
		layoutInfo.set(layoutEl.getAttributeNS('ref'), info );
	}*/
	
	override public function setXml(value:XML):XML
	{
		//trace(value.toXMLString());
		super.setXml(value);
		//TODO:set box from svg
		svgRoot.addEventListener(SVGEvent.SVGLoad, layout);
		return value;
	}
	
	///TOOLS SECTION - TODO:TO BE MOVED INTO SEPARATE CLASS
	
	public static function getSize(di:DisplayObject, sX:Float, sY:Float, angle:Float = 0.0):Int
	{
		var size:Int = 0;
		var dS:Sprite = new Sprite();
		Lib.current.addChild(dS);
		var gfx:Graphics = dS.graphics;
		gfx.lineStyle(1, 0xff00ff);
		trace(sX + ', ' +sY);
		switch(angle)
		{
			case 0.0:
			//from left to right
			case Math.PI / 2:
			//from bottom to top
			//while (di.hitTestPoint(sX, sY, true))
			while ( sY>-1)
			{
				if (di.hitTestPoint(sX, sY, true))
				{
					if (size == 0)
						gfx.moveTo(sX, sY);
					trace('yes:' + size + ' sY:' +sY);
					size += 1;
					gfx.lineTo(sX, sY-1);					
				}
				else if (size > 0)
					break;
				sY -= 1;
			}
			case Math.PI:
			//from right to left
			case 1.5 * Math.PI:
			//from top to bottom
			default:
			//calculate angle			
			
		}
		return size;
	}
	
	override public function addActionListener(eventType:String, target:EventDispatcher):Void 
	{
		target.addEventListener(MouseEvent.CLICK, onClickHandler);

	}
	
	function onClickHandler(evt:MouseEvent)
	{
		var svgNode:SVGNode = cast (evt.target.svgNode, SVGNode);
		trace(svgNode.xml.toXMLString());
	}
}